package com.my.ry.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSONObject;
import com.my.ry.common.jwt.Jwt;
import com.my.ry.common.jwt.TokenState;
import com.my.ry.common.util.PropertyUtil;


/**
 * 登录过滤
 * 
 * @author WF
 */
public class LoginFilter extends OncePerRequestFilter {
	
	private static Logger logger = LogManager.getLogger(LoginFilter.class.getName());

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//不校验token的接口和页面
		String[] notFilter = new String[] {"/", "login.jsp", "/user/login", "/pages/users.jsp"};
		String URI = request.getRequestURI();
		logger.info("URI:"+URI);
//		logger.info("ContextPath:"+request.getContextPath());
		String token = request.getHeader("token");
		
		//当header中没有token，从cookies中获取token
		if(token == null || token.isEmpty()){
			//从cookie中获取token
			Cookie[] cookies = request.getCookies();
			if(cookies != null){
				for (Cookie c : cookies) {
			 		if (c.getName().equals("token")) {
			 			token = c.getValue();
			 		}
			 	}
			}
		}
		
		//校验token
		Map<String, Object> resultMap = Jwt.validToken(token);
		TokenState state = TokenState.getTokenState((String)resultMap.get("state"));
		switch (state) {
			case VALID:
				//取出payload中数据,放入到request作用域中
				request.setAttribute("user_info", resultMap.get("data"));
				//设置数据源
				@SuppressWarnings("unchecked")
				Map<String, Object> userMap = (Map<String, Object>) resultMap.get("data");
				
				//如果请求登录页，则跳转用户首页
				if(URI.endsWith("/") || URI.endsWith("login.jsp")){
					String redirect = PropertyUtil.getProperty("userIndex");;
					/*String u_role = userMap.get("u_role").toString();
					if("1".equals(u_role)){//教师
						redirect = PropertyUtil.getProperty("teacherIndex");
					}
					if("2".equals(u_role)){//学生
						redirect = PropertyUtil.getProperty("studentIndex");
					}
					if("0".equals(u_role)){//校管理员
						redirect = PropertyUtil.getProperty("adminIndex");
					}
					if("99".equals(u_role)){//超管
						redirect = PropertyUtil.getProperty("superAdminIndex");
					}*/
					response.sendRedirect(request.getContextPath() + redirect);
					return;
				}
				//放行
				filterChain.doFilter(request, response);
				break;
			case EXPIRED:
			case INVALID:
			default:
				//匹配是否校验token
				for (String s : notFilter) {
					if (URI.endsWith(s)) {
						//不校验token，直接放行
						filterChain.doFilter(request, response);
						return;
					}
				}
				
				//token过期或者无效，跳转登陆页
				if (URI.endsWith(".jsp")) {
					response.sendRedirect("/login.jsp");
				}else{
					JSONObject outputMsg = new JSONObject();
					outputMsg.put("success", false);
					outputMsg.put("message", "token无效，请重新登陆");
					output(outputMsg.toString(), response);
				}
				break;
		}

	}
	
	public void output(String jsonStr, HttpServletResponse response) throws IOException{
		response.setContentType("application/json;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		out.write(jsonStr);
		out.flush();
		out.close();
	}
}